package com.waypolice.manager.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.waypolice.base.BaseController;
import com.waypolice.common.pojo.UpmsResult;
import com.waypolice.common.pojo.UpmsResultConstant;
import com.waypolice.common.utils.*;
import com.waypolice.manager.service.CmsSinItemService;
import com.waypolice.manager.service.PDFFileConversionService;
import com.waypolice.manager.service.UpmsArchivesTypesService;
import com.waypolice.manager.service.VolAndItemService;
import com.waypolice.mapper.CmsSinItemMapper;
import com.waypolice.pojo.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.InputStream;
import java.util.*;

/**
 * @Description  单件著录
 * @Author wangrang
 * @Date Created in 17:08 2019/3/22
 * @Modified By:
 */
@Controller
@Api(value = "单件著录", description = "单件著录进行操作")
@RequestMapping(value="/pcwindow")
public class VItemRecordAction extends BaseController {
    private static final Logger LOGGER = LoggerFactory.getLogger(VItemRecordAction.class);

    @Autowired
    private CmsSinItemMapper cmsSinItemMapper;

    @Autowired
    private CmsSinItemService cmsSinItemService;

    @Value("${IMAGE_SERVER_URL}")
    private String IMAGE_SERVER_URL;

    @Autowired
    private UpmsArchivesTypesService upmsArchivesTypesService;

    @Autowired
    private VolAndItemService volAndItemService;

    @Autowired
    private PDFFileConversionService pdfFileConversionService;

    /**
     * @author:wr
     * @description 跳转单件著录页面
     * @date:
     * @return
     */
    @ApiOperation(value = "跳转到单件著录页面")
    @RequiresPermissions("cms:item:record")
    @RequestMapping("/arcRecord")
    public String toItemRecord(){
        return "preArchive/singelRecordItem";
    }

    @RequestMapping("/sin/carrierType")
    public String carrierType() {
        return "preArchive/carrierTypeSingle";
    }

    @ApiOperation(value = "单件数据查询")
    @RequestMapping(value = "/sin/itemSinList", method = RequestMethod.GET)
    @ResponseBody
    public Object itemSinList(HttpServletRequest request,
                          @RequestParam(required = false, defaultValue = "0", value = "offset") int offset,
                          @RequestParam(required = false, defaultValue = "10", value = "limit") int limit,
                          @RequestParam(required = false, value = "sort") String sort,
                          @RequestParam(required = false, value = "order") String order,
                          String sin_itemTitle, String sin_itemType,String sin_Storagelocation,String sinStatus) {

        CmsSinItemExample cmsSinItemExample = new CmsSinItemExample();
        CmsSinItemExample.Criteria criteria = cmsSinItemExample.createCriteria();
        if(StringUtils.isNotBlank(sin_itemTitle)){
            criteria.andItemTitleLike("%"+sin_itemTitle+"%");}
        if(StringUtils.isNotBlank(sin_itemType)){
            criteria.andItemExp1EqualTo(sin_itemType);
        }
        if(StringUtils.isNotBlank(sin_Storagelocation)){
            criteria.andItemStoragelocationEqualTo(sin_Storagelocation);
        }
        if(StringUtils.isNotBlank(sinStatus)){
            criteria.andItemArcStatusEqualTo(Long.valueOf(sinStatus));
        }else {
            //著录
            criteria.andItemArcStatusEqualTo(0L);
        }
        if (StringUtils.isNotBlank(sort) && StringUtils.isNotBlank(order)) {
            sort= StringUtil.frontStrongToOracleString(sort);
            cmsSinItemExample.setOrderByClause(sort + " " + order);
        }else {
            cmsSinItemExample.setOrderByClause("\"ITEM_CREATE_DATE\" DESC");
        }
        List<CmsSinItem> cmsSinItem = cmsSinItemService.selectAllByQueryParms(cmsSinItemExample);

        //最终的list集合,分页操作
        PageUtils<CmsSinItem> pageUtils = new PageUtils<CmsSinItem>();
        List<CmsSinItem> cmsSinItemPage = pageUtils.pageList(cmsSinItem, offset, limit);

        Map<String, Object> result = new HashMap<>();
        result.put("rows",cmsSinItemPage);
        result.put("total",cmsSinItem.size());
        return result;
    }

    /**
     * 单件著录信息新增
     *
     * @return user
     */
    @ApiOperation(value = "新增单件")
    @RequestMapping(value = "/sin/save", method = RequestMethod.POST)
    @ResponseBody
    public String save( HttpServletRequest request,@RequestParam(required = false, value = "cmsSinItem")String cmsSinItem) {
        CmsSinItem cmsSinItem1 = JSONObject.parseObject(cmsSinItem, CmsSinItem.class);
        int i = cmsSinItemMapper.insertSelective(cmsSinItem1);
        return String.valueOf(i);
    }

    @ApiOperation(value = "单件获取原文地址")
    @RequestMapping(value = "/sin/viewSinItemOriginal", method = RequestMethod.POST)
    @ResponseBody
    public String viewItemUrl(HttpServletRequest request, HttpSession session, Long itemId) {
        String url = cmsSinItemService.selectByPojo(itemId);
        if(StringUtils.isNotBlank(url)){
            return url;
        }else {
            return "failure";
        }
    }

    @ApiOperation(value = "删除卷和件的著录信息")
    @RequestMapping(value = "/sin/deleteSin", method = RequestMethod.POST)
    @ResponseBody
    public String deleteVolumeAndItem(HttpServletRequest request,String idsSin) {
        if(StringUtils.isNotBlank(idsSin)){
            String[] split = idsSin.split("-");
            for (String s : split) {
                CmsSinItem cmsSinItem = cmsSinItemMapper.selectByPrimaryKey(Long.valueOf(s));
                //删除原文
                if("1".equals(cmsSinItem.getItemStr3()) && StringUtils.isNotBlank(cmsSinItem.getItemStr2())){
                    FastDfsClient fastDFSClient = null;
                    try {
                        fastDFSClient = new FastDfsClient("classpath:client.conf");
                    } catch (Exception e) {
                        e.printStackTrace();
                        LOGGER.error("FastDfs连接异常,"+e);
                    }
                    String trim = cmsSinItem.getItemStr2().replaceAll(IMAGE_SERVER_URL, "").trim();
                    fastDFSClient.deleteFile(trim);
                }
                int i = cmsSinItemMapper.deleteByPrimaryKey(Long.valueOf(s));
            }
            return "success";
        }
        return "请选中一行数据!";
    }

    @ApiOperation(value = "归档")
    @RequestMapping(value = "/sin/submitSinItem", method = RequestMethod.POST)
    @ResponseBody
    public String submitSinItem(HttpServletRequest request,String idsSinOne) {
        if(StringUtils.isNotBlank(idsSinOne)){
            String errorInfo=null;
            String[] idArraySin = idsSinOne.split("-");
            int sinItemFlag=0;
            for (String itemId : idArraySin) {
                CmsSinItem cmsSinIt = cmsSinItemMapper.selectByPrimaryKey(Long.valueOf(itemId));
                //归档日期
                cmsSinIt.setItemStr1Date(DateTimeUtil.getNow());
                cmsSinIt.setItemArcStatus(1L);
                //修改日期
                cmsSinIt.setItemEditDate(DateTimeUtil.getNow());
                //载体类型
                String itemCarrier = cmsSinIt.getItemCarrier();
                if(StringUtils.isBlank(itemCarrier)){
                    cmsSinIt.setItemArcStatus(3L);
                    cmsSinIt.setItemExp5("3");
                    int i1 = cmsSinItemMapper.updateByPrimaryKey(cmsSinIt);
                    sinItemFlag+=1;
                    continue;
                }
                //仅实体不进行原文校验
                if(!"0".equals(itemCarrier)){
                    //判断是否完成挂接原文
                    if(StringUtils.isBlank(cmsSinIt.getItemStr2())){
                        cmsSinIt.setItemArcStatus(3L);
                        cmsSinIt.setItemExp5("1");
                        int i1 = cmsSinItemMapper.updateByPrimaryKey(cmsSinIt);
                        sinItemFlag+=1;
                        continue;
                    }
                }



                //生成档号
                String fileNumber = null;
                try {
                    fileNumber = cmsSinItemService.getSingItemFileNumber(cmsSinIt);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                //件号错误，或者著录项为空
                if("error".equals(fileNumber) || StringUtils.isBlank(fileNumber)){
                    cmsSinIt.setItemArcStatus(3L);
                    cmsSinIt.setItemExp5("2");
                    int i1 = cmsSinItemMapper.updateByPrimaryKey(cmsSinIt);
                    sinItemFlag+=1;
                    continue;
                }
                if(StringUtils.isNotBlank(cmsSinIt.getItemStr1()) && !fileNumber.trim().equals(cmsSinIt.getItemStr1().trim())){
                    //原档号和现档号不同
                    cmsSinIt.setItemExp6(fileNumber);
                    cmsSinIt.setItemArcStatus(3L);
                    cmsSinIt.setItemExp5("4");
                    int i1 = cmsSinItemMapper.updateByPrimaryKey(cmsSinIt);
                    sinItemFlag+=1;
                    continue;
                }else {
                    cmsSinIt.setItemStr1(fileNumber);
                    int i = cmsSinItemMapper.updateByPrimaryKey(cmsSinIt);
                }
            }

            if(sinItemFlag ==0){
                return "success";
            }else {
                return "归档失败"+sinItemFlag+"件,请查看归档失败列表。";
            }
        }
        return "请选中一行数据!";
    }

    @ApiOperation(value = "原件号强制归档")
    @RequestMapping(value = "/sinItemErrorArchive", method = RequestMethod.POST)
    @ResponseBody
    public String sinItemErrorArchive(HttpServletRequest request,String sinItemId,String sinArchiveStatus) {
            CmsSinItem cmsSinIt = cmsSinItemMapper.selectByPrimaryKey(Long.valueOf(sinItemId));
            //归档日期
            cmsSinIt.setItemStr1Date(DateTimeUtil.getNow());
            cmsSinIt.setItemArcStatus(1L);
            //修改日期
            cmsSinIt.setItemEditDate(DateTimeUtil.getNow());
            //载体类型
            String itemCarrier = cmsSinIt.getItemCarrier();
            if(StringUtils.isBlank(itemCarrier)){
                return "载体类型不能为空！";
            }
            //仅实体不进行原文校验
            if(!"0".equals(itemCarrier)){
                //判断是否完成挂接原文
                if(StringUtils.isBlank(cmsSinIt.getItemStr2())){
                    return "未挂接原文!";
                }
            }

            //生成档号
            String fileNumber = null;
            try {
                fileNumber = cmsSinItemService.getSingItemFileNumber(cmsSinIt);
            } catch (Exception e) {
                e.printStackTrace();
            }
            //件号错误，或者著录项为空
            if("error".equals(fileNumber) || StringUtils.isBlank(fileNumber)){
               return "构成件号的著录项不能为空！";
            }
            if(StringUtils.isNotBlank(sinArchiveStatus)&&"1".equals(sinArchiveStatus)){
                //系统生成的新件号归档
                cmsSinIt.setItemStr1(fileNumber);
            }
            cmsSinIt.setItemArcStatus(1L);
            int i = cmsSinItemMapper.updateByPrimaryKey(cmsSinIt);
            if(i==0){
                return "归档失败！";
            }else {
                return "success";
            }
    }

    /**
     * 查询全部案卷类型
     * @param response
     * @param request
     * @return
     */
    @ApiOperation(value = "查询全部案卷类型")
    @RequestMapping("/findType/findTypeBySortNum")
    @ResponseBody
    public  List<UpmsArchivesTypes> findTypeBySortNum(HttpServletResponse response, HttpServletRequest request) {
        List<UpmsArchivesTypes> allTypes = upmsArchivesTypesService.findAllTypes();
        return allTypes;
    }

    @ApiOperation(value = "单件上传Excel")
    @RequestMapping(value = "/singleImportExcel", method = RequestMethod.POST)
    @ResponseBody
    public String singleImportExcel(@RequestParam(value="singleExcelFile",required=false)MultipartFile singleExcelFile,
                              HttpServletRequest request,String dataBaseImportFields) {
        JSONObject jsonObject = JSONObject.parseObject(dataBaseImportFields);
        try {
            InputStream inputStream = singleExcelFile.getInputStream();
            String fileName = singleExcelFile.getOriginalFilename();
            if(!"xls".equals(fileName.split("\\.")[1]) && !"xlsx".equals(fileName.split("\\.")[1])){
                return "请选择正确的文件格式!";
            }
            long size = singleExcelFile.getSize();
            ReadExcelUtils readExcelUtils = new ReadExcelUtils(inputStream,fileName);
            //form为0,获取Excel中第一张表格
            int excelSheetOne = getSingleExcelSheetOne(readExcelUtils, jsonObject);

            if(excelSheetOne!=0){
                return excelSheetOne+"行数据上传失败!";
            }
            return "success";
        } catch (Exception e) {
            LOGGER.error("异常:"+e);
            return "Erro：数据导入错误";
        }
    }

    /**
     * 单件导入获取Excel中第一个表
     * @param readExcelUtils
     * @return
     * @throws Exception
     */
    private int getSingleExcelSheetOne(ReadExcelUtils readExcelUtils,JSONObject jsonObject) throws Exception {
        List<Map<String, Object>> excelOne = readExcelUtils.readExcelContent(0);
        int count=0;
        for (Map<String, Object> stringObjectMap : excelOne) {
            CmsSinItem cmsSinItem = new CmsSinItem();
            for (String key : jsonObject.keySet()) {
                String value = jsonObject.get(key).toString();
                String o = stringObjectMap.get(value) == null ? null : stringObjectMap.get(value).toString();
                Object fieldValue = stringObjectMap.get(value) == null ? null : stringObjectMap.get(value);
                ReflectionObjectUtil.invokeSet(cmsSinItem,key,fieldValue);
            }
            //年度
            String itemExp3 = cmsSinItem.getItemExp3();
            if(StringUtils.isNotBlank(itemExp3) && itemExp3.contains(".")){
                String itemExp3Substr = itemExp3.substring(0, itemExp3.indexOf("."));
                cmsSinItem.setItemExp3(itemExp3Substr);
            }
            //文件类型
            String itemExp1 = cmsSinItem.getItemExp1();
            if(StringUtils.isNotBlank(itemExp1) && itemExp1.contains(".")){
                String itemExp1Substr = itemExp1.substring(0, itemExp1.indexOf("."));
                cmsSinItem.setItemExp1(itemExp1Substr);
            }
            //保管期限
            String itemNum = cmsSinItem.getItemNum();
            if(StringUtils.isNotBlank(itemNum) && itemNum.contains(".")){
                String itemNumSubstr = itemNum.substring(0, itemNum.indexOf("."));
                cmsSinItem.setItemNum(itemNumSubstr);
            }
            //密级
            String itemSecret = cmsSinItem.getItemSecret();
            if(StringUtils.isNotBlank(itemSecret) && itemSecret.contains(".")){
                String itemSecretSubstr = itemSecret.substring(0, itemSecret.indexOf("."));
                cmsSinItem.setItemSecret(itemSecretSubstr);
            }

            int i = cmsSinItemMapper.insertSelective(cmsSinItem);
            if(i==0){
                count+=1;
            }
        }
        return count;
    }



    /**
     * @author:zyp
     * @description 根据id获取单件数据
     * @date: 2019/3/27 11:05
     * @return 
     */
    @ApiOperation(value = "根据id获取单件数据")
    @RequestMapping(value = "/sin/itemSinById/{fileId}")
    @ResponseBody
    public Object itemSinById(@PathVariable("fileId") Long fileId, HttpServletRequest request, HttpSession session) {
        CmsSinItem cmsSinItem = cmsSinItemService.selectSinItemById(fileId);
        List<CmsSinItem> cmsSinItems = new ArrayList<>();
        cmsSinItems.add(cmsSinItem);
        Map<String, Object> result = new HashMap<>();
        result.put("rows",cmsSinItems);
        result.put("total",cmsSinItems.size());
        return result;
    }

    /**
     * 单件著录信息编辑查询
     *
     * @return user
     */
    @ApiOperation(value = "编辑查询")
    @RequestMapping(value = "/sin/edit", method = RequestMethod.POST)
    @ResponseBody
    public Object edit( HttpServletRequest request,String idEdit) {
        CmsSinItem cmsSinItem = cmsSinItemMapper.selectByPrimaryKey(Long.valueOf(idEdit));

        net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject.fromObject(cmsSinItem);
        String string = jsonObject.toString();
        return new UpmsResult(UpmsResultConstant.SUCCESS, string);
    }

    /**
     * 单件著录信息编辑提交
     *
     * @return user
     */
    @ApiOperation(value = "编辑提交")
    @RequestMapping(value = "/sin/editSubmit", method = RequestMethod.POST)
    @ResponseBody
    public String editSubmit( HttpServletRequest request,@RequestParam(required = false, value = "cmsSinItemEdit")String cmsSinItemEdit) {
        CmsSinItem cmsSinEdit = JSONObject.parseObject(cmsSinItemEdit, CmsSinItem.class);

        int i1 = cmsSinItemMapper.updateByPrimaryKeySelective(cmsSinEdit);

        return String.valueOf(i1);
    }


}
